//
//  LookHistoryVC.m
//  yunbaolive
//
//  Created by ybRRR on 2020/1/18.
//  Copyright © 2020 cat. All rights reserved.
//

#import "LookHistoryVC.h"
#import "LookHistoryCell.h"
#import "LookHistoryModel.h"
#import "CommodityDetailVC.h"
#import "HistoryListModel.h"
#import "NSObject+MJKeyValue.h"
#import "OutsideGoodsDetailVC.h"
@interface LookHistoryVC ()<UITableViewDataSource, UITableViewDelegate>
{
    BOOL manageSel;
    BOOL isAllSel;
    BOOL sectionSel;
    UIView *bottomView;
    
    int pageIndex;
    //已选的商品集合
    NSMutableArray *selectHistory;
    UIButton *allSelBtn;
    UIButton *sectionBtn;
    
    NSInteger  sectionIndex;
    NSMutableArray *sectionArr;
    UIButton *deleteBtn;
}
@property (nonatomic, strong)UITableView *historyTable;
@property (nonatomic, strong)UIView *headerView;

@property (nonatomic, strong)NSMutableArray *infos;
@property (nonatomic,strong)NSMutableDictionary *dic;
@property (nonatomic, strong)NSMutableArray *listArr;

@end

@implementation LookHistoryVC
/// 懒加载indexpath字典
- (NSMutableDictionary *)dic {
    if (_dic == nil) {
        _dic = [NSMutableDictionary dictionary];
    }
    return _dic;
}
#pragma mark-------请求数据---------
-(void)requstData{
    NSString *url = [purl stringByAppendingFormat:@"?service=Buyer.getGoodsVisitRecord"];
    
    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"p":@(pageIndex)
                          };
    [WYNetworking postWithUrl:@"Buyer.getGoodsVisitRecord" Dic:dic Suc:^(int code, id info, NSString *msg) {
        [self.historyTable.mj_header endRefreshing];
        [self.historyTable.mj_footer endRefreshing];
        if (code == 0) {
            NSArray *infoArr  = info;
            if (pageIndex == 1) {
                [self.infos removeAllObjects];
                [sectionArr removeAllObjects];
                [selectHistory removeAllObjects];
                [_listArr removeAllObjects];
                
                NSMutableArray *array = [NSMutableArray array];
                for (NSDictionary *dic in infoArr) {
                    HistoryListModel *model = [HistoryListModel mj_objectWithKeyValues:dic];
                    [array addObject:model];
                }
                [_listArr addObjectsFromArray:array];

                if (infoArr.count < 1) {
                    self.rightBtn.hidden = YES;
                    [PublicView showImgNoData:self.historyTable name:@"shop_无数据" text:YZMsg(@"近期暂无浏览记录")];
                }else{
                    self.rightBtn.hidden = NO;
                    [PublicView hiddenImgNoData:self.historyTable];
                }
            }else{
                self.rightBtn.hidden = NO;
                NSMutableArray *array = [NSMutableArray array];
                for (NSDictionary *dic in infoArr) {
                    HistoryListModel *model = [HistoryListModel mj_objectWithKeyValues:dic];
                    [array addObject:model];
                }
                [_listArr addObjectsFromArray:array];

            }
            [self.infos addObjectsFromArray:infoArr];
            

            [self.historyTable reloadData];
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            [self.historyTable.mj_header endRefreshing];
            [self.historyTable.mj_footer endRefreshing];

        }];

}
-(void)initData{
    pageIndex = 1;
    self.infos = [NSMutableArray array];
    selectHistory = [NSMutableArray array];
    sectionArr = [NSMutableArray array];
    _listArr = [NSMutableArray array];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleL.text = YZMsg(@"浏览记录");
    self.rightBtn.hidden = NO;
    [self.rightBtn setTitle:YZMsg(@"管理") forState:0];
    [self.rightBtn setTitleColor:[UIColor blackColor] forState:0];
    [self initData];
    [self.view addSubview:self.historyTable];
    
    [self creatBottomView];
    
    [self requstData];
}
-(void)rightBtnClick
{
    manageSel = !manageSel;
    if (manageSel) {
        [self.rightBtn setTitle:YZMsg(@"取消") forState:0];
        bottomView.hidden = NO;
        self.historyTable.frame = CGRectMake(0, 64+statusbarHeight, _window_width, _window_height-64-statusbarHeight-50);
    }else{
        [self.rightBtn setTitle:YZMsg(@"管理") forState:0];
        bottomView.hidden = YES;
        self.historyTable.frame = CGRectMake(0, 64+statusbarHeight, _window_width, _window_height-64-statusbarHeight);

    }
    [self.historyTable reloadData];
}
-(void)creatBottomView{
    bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, _window_height-50, _window_width, 50)];
    [self.view addSubview:bottomView];
    
    allSelBtn = [UIButton buttonWithType:0];
    allSelBtn.frame = CGRectMake(0, 10, 80, 40);
    [allSelBtn setImage:[UIImage imageNamed:@"记录未选"] forState:0];
    [allSelBtn setImage:[UIImage imageNamed:@"记录选中"] forState:UIControlStateSelected];
    [allSelBtn setTitle:YZMsg(@"全选") forState:0];
    allSelBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [allSelBtn setTitleColor:[UIColor blackColor] forState:0];
    [allSelBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
    [allSelBtn addTarget:self action:@selector(allSelClick:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:allSelBtn];
    
    deleteBtn = [UIButton buttonWithType:0];
    deleteBtn.frame = CGRectMake(_window_width-90, 10, 90, 40);
    [deleteBtn setBackgroundColor:Normal_Color];
    [deleteBtn setTitle:YZMsg(@"删除") forState:0];
    [deleteBtn setTitleColor:[UIColor whiteColor] forState:0];
    deleteBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [deleteBtn addTarget:self action:@selector(deleteClick) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:deleteBtn];
    
    bottomView.hidden = YES;
}
-(UITableView *)historyTable{
    if (!_historyTable) {
        _historyTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 64+statusbarHeight, _window_width, _window_height-64-statusbarHeight) style:UITableViewStylePlain];
        _historyTable.delegate = self;
        _historyTable.dataSource = self;
        _historyTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _historyTable.mj_header = [MJRefreshHeader headerWithRefreshingBlock:^{
            pageIndex = 1;
            [self requstData];
        }];
        _historyTable.mj_footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
            pageIndex ++;
            [self requstData];

        }];
    }
    return _historyTable;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.listArr.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    HistoryListModel * tempModle = (HistoryListModel*)self.listArr[section];
    return tempModle.list.count;

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LookHistoryCell *cell = [LookHistoryCell cellWithTab:tableView andIndexPath:indexPath];
    if (manageSel) {
        cell.selBtn.hidden =NO;
        [cell.selBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(30);
        }];
    }else{
        cell.selBtn.hidden = YES;
        [cell.selBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(0);
        }];
    }
    LookHistoryModel *models =((HistoryListModel*)self.listArr[indexPath.section]).list[indexPath.row];
    cell.model = models;
    
    // 给cell做标记
    cell.tag = (long)indexPath.section *100 + (long)indexPath.row;
    NSString * cellTag = [NSString stringWithFormat:@"%zd",cell.tag];

    NSDictionary* _tempDic = @{
                 cellTag:indexPath
                 };
    [self.dic addEntriesFromDictionary:_tempDic];

    [cell layoutSubviews];
    return cell;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    HistoryListModel*listModel = self.listArr[section];
    _headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"ShopHistoryHeader"];
    if (_headerView == nil) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 40)];
        _headerView.backgroundColor = [UIColor whiteColor];

    }
    _headerView.tag = section;

    UILabel *dateLb = [[UILabel alloc]init];
    dateLb.font = [UIFont boldSystemFontOfSize:16];
    dateLb.textColor = [UIColor blackColor];
    [_headerView addSubview:dateLb];
    dateLb.text = [self.infos[section] valueForKey:@"date"];

    sectionBtn = [UIButton buttonWithType:0];
    sectionBtn.frame = CGRectMake(15, 8, 22, 22);
    sectionBtn.tag = section;
    [sectionBtn setImage:[UIImage imageNamed:@"记录未选"] forState:UIControlStateNormal];
    [sectionBtn setImage:[UIImage imageNamed:@"记录选中"] forState:UIControlStateSelected];
    [sectionBtn addTarget:self action:@selector(sectionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:sectionBtn];
    sectionBtn.hidden = YES;
    
    if (manageSel) {
        sectionBtn.hidden = NO;
        dateLb.frame = CGRectMake(sectionBtn.right+10, 8, _window_width, 22);
    }else{
        sectionBtn.hidden = YES;
        dateLb.frame = CGRectMake(15, 8, _window_width, 22);
    }
    sectionBtn.selected = listModel.groupSelected;
    if (listModel.list.count == 0) {
        return nil;
    }
    return self.headerView;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    LookHistoryModel *models =((HistoryListModel*)self.listArr[indexPath.section]).list[indexPath.row];
    if (manageSel) {
        LookHistoryCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        models.isSelected = !models.isSelected;
        cell.selBtn.selected = !cell.selBtn.selected;
        //判断组的是否选中状态是否修改
        NSString * cellTagStr = [NSString stringWithFormat:@"%zd",cell.tag];
        NSIndexPath *indexPath = self.dic[cellTagStr];
        HistoryListModel * listModel = (HistoryListModel*)self.listArr[indexPath.section];
        //0.便利当前组cell上选中按钮的个数
        NSInteger seletedNum =0;

        for (LookHistoryModel* goodsModel in listModel.list) {
            if (goodsModel.isSelected) {
                seletedNum += 1;
            }
            // 1.当前组的cell的个数 是否等于 勾选的总数
            if (((HistoryListModel*)self.listArr[indexPath.section]).list.count == seletedNum) {
                listModel.groupSelected = YES; //cell改变组头变为选中
                //判断  //cell改变组头 //组头改变全选
                NSInteger selectedNum = 0 ;
                for (HistoryListModel * tempListModel in self.listArr) {//遍历所有组
                    if (tempListModel.groupSelected) {//如果组头是选中的
                        selectedNum += 1;
                    }
                    if (selectedNum == self.listArr.count) {
                        allSelBtn.selected = YES;
                    }
                }
            } else {
                listModel.groupSelected = NO;
                allSelBtn.selected = NO;
            }
            [_historyTable reloadData];
        }
    }else{
        if (![models.goods_status isEqual:@"1"]) {
            [MBProgressHUD showError:YZMsg(@"商品不存在~")];
            return;
        }
        if ([models.type isEqual:@"1"]) {
            OutsideGoodsDetailVC *detail = [[OutsideGoodsDetailVC alloc]init];
            detail.goodsID = models.goodsid;
            detail.liveUid = models.uid;
            [[YBBaseAppDelegate sharedAppDelegate] pushViewController:detail animated:YES];

        }else{
            CommodityDetailVC *detail = [[CommodityDetailVC alloc]init];
            detail.goodsID = models.goodsid;
            detail.liveUid = models.uid;
            [[YBBaseAppDelegate sharedAppDelegate] pushViewController:detail animated:YES];
        }
    }
}

-(void)sectionBtnClick:(UIButton *)sender{
    sender.selected = !sender.selected;
    [self headerSelectedBtnClick:sender.tag];
}
#pragma mark-----全部选择--------
-(void)allSelClick: (UIButton*)allSelectedBtn{
    allSelectedBtn.selected = !allSelectedBtn.selected; // 修改全选按钮的状态
    if (allSelectedBtn.selected) { // 如果全选按钮改变了为选中
        for (int i = 0; i <self.listArr.count; i ++) {
            HistoryListModel * listModel = self.listArr[i];
            if (!listModel.groupSelected) {//遍历如果组不是选中状态
                [self headerSelectedBtnClick:i]; //模拟组头点击了一次
            }
        }
    }else{
        for (int i = 0; i < self.listArr.count; i ++) { // 遍历所有的组头点击
            [self headerSelectedBtnClick:i];
        }
    }
}
- (void)headerSelectedBtnClick:(NSInteger)section {
    HistoryListModel*listModel = self.listArr[section];
    listModel.groupSelected = !listModel.groupSelected;
    // 判断如果点击 | header选中
    if (listModel.groupSelected) {
        //    /// 判断组头的点击改变全选按钮
        NSInteger tempGroupSelectNum = 0;
        for (HistoryListModel *model in  self.listArr) {
            if (model.groupSelected) {
                tempGroupSelectNum ++;
            }
            if (tempGroupSelectNum ==  self.listArr.count) {
                allSelBtn.selected = YES;
            }
        }
        for (LookHistoryModel* goodsModel in listModel.list) {
            if (!goodsModel.isSelected) {                                       //下面不是选中状态的cell
                goodsModel.isSelected = YES;
            }
        }
    } else {  // 取消header选中 所有都取消
        //全选按钮变为不选中
        allSelBtn.selected = NO;
        for (LookHistoryModel* goodsModel in listModel.list) {
            goodsModel.isSelected = NO;
        }
    }
    
    [_historyTable reloadData];
}

#pragma mark-----删除操作--------
-(void)deleteClick{
    [selectHistory removeAllObjects];
    for (int i = 0; i < self.listArr.count; i ++) {
        HistoryListModel*listModel = self.listArr[i];
        for (LookHistoryModel* goodsModel in listModel.list) {
            if (goodsModel.isSelected) {
                [selectHistory addObject:goodsModel];
            }
        }
    }
    if (selectHistory.count < 1) {
        [MBProgressHUD showError:YZMsg(@"请先选择要删除内容")];
        return;;
    }
    NSLog(@"------------sel:%@  \n ====:%ld",selectHistory, selectHistory.count);
    NSString *delId = @"";
    for (LookHistoryModel *model in selectHistory) {
        delId = [delId stringByAppendingFormat:@"%@,",model.idStr];
    }
    NSRange range = NSMakeRange(delId.length-1, 1);
    delId = [delId stringByReplacingCharactersInRange:range withString:@""];

    NSString *url = [purl stringByAppendingFormat:@"?service=Buyer.delGoodsVisitRecord"];

    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken], @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                          @"recordids":delId,
                          @"sign":sign
                          };
    NSLog(@"-=-=-=-=:%@", dic);
    [WYNetworking postWithUrl:@"Buyer.delGoodsVisitRecord" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            [MBProgressHUD showError:msg];
            [self requstData];
            [self rightBtnClick];
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
        }];

}
@end
